package gin_http

import (
	"gitee.com/captials-team/ubdframe/src/domain/dto/reqdata"
	"gitee.com/captials-team/ubdframe/src/domain/dto/respdata"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/mojocn/base64Captcha"
	"net/http"
)

var captchaStore = base64Captcha.DefaultMemStore
var captchaDriver = base64Captcha.DefaultDriverDigit

// CaptchaController 验证码图片相关Controller
type CaptchaController struct {
	Store  base64Captcha.Store
	Driver *base64Captcha.DriverDigit
}

func (ctr *CaptchaController) GetCaptcha(ctx *gin.Context) {
	c := base64Captcha.NewCaptcha(ctr.CaptchaDriver(), ctr.CaptchaStore())
	id, b64s, answer, err := c.Generate()
	if err != nil {
		ctx.JSON(http.StatusOK, respdata.CSysBusy.MMsg("CAPTCHA_ERR"))
		return
	}

	v1log.Out.Debug("captcha %s - %s", id, answer)

	ctx.JSON(http.StatusOK, respdata.CSuccess.MData(respdata.CaptchaResponse{Key: id, Image: b64s}))
	return
}

func (ctr *CaptchaController) VerifyCaptcha(ctx *gin.Context) {
	var req reqdata.CaptchaVerifyReq

	ctx.ShouldBindBodyWith(&req, binding.JSON)
	//验证码验证
	if !ctr.CaptchaStore().Verify(req.CaptchaKey, req.CaptchaCode, true) {
		ctx.AbortWithStatusJSON(http.StatusOK, respdata.CVtCodeInvalid)
		return
	}
	ctx.JSON(http.StatusOK, respdata.CSuccess)
	return
}

func (ctr *CaptchaController) CaptchaStore() base64Captcha.Store {
	if ctr.Store != nil {
		return ctr.Store
	}
	return captchaStore
}
func (ctr *CaptchaController) CaptchaDriver() base64Captcha.Driver {
	if ctr.Driver != nil {
		return ctr.Driver
	}
	return captchaDriver
}

func (ctr *CaptchaController) VerifyHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req reqdata.CaptchaVerifyReq

		ctx.ShouldBindBodyWith(&req, binding.JSON)
		//验证码验证
		if !ctr.CaptchaStore().Verify(req.CaptchaKey, req.CaptchaCode, true) {
			ctx.AbortWithStatusJSON(http.StatusOK, respdata.CVtCodeInvalid)
			return
		}
	}
}

func NewCaptchaController() *CaptchaController {
	return &CaptchaController{}
}
